package blue.base.core.util;

import java.net.FileNameMap;
import java.net.URLConnection;

/**
 * @author Jin Zheng
 * @since 1.0 2021-07-30
 */
public class PathUtil {
	public static final int NOT_EXIST = -1;
	public static final String SLASH = "/";
	public static final int SLASH_LEN = SLASH.length();
	public static final String DOUBLE_SLASH = "//";
	public static final int DOUBLE_SLASH_LEN = DOUBLE_SLASH.length();
	public static final String DOT = ".";

	private PathUtil() {
	}

	/**
	 * 取得主机的名称
	 *
	 * @param url 网页地址
	 * @return 主机名称
	 */
	public static String getHost(String url) {
		int start = url.indexOf(DOUBLE_SLASH);
		int end = url.indexOf(SLASH, start + DOUBLE_SLASH_LEN);
		if (end != NOT_EXIST) {
			return url.substring(start + DOUBLE_SLASH_LEN, end);
		}
		else {
			return url.substring(start + DOUBLE_SLASH_LEN);
		}
	}

	/**
	 * 取得文件的名称
	 *
	 * @param url URL地址
	 * @return 文件名称
	 */
	public static String getFileName(String url) {
		int pos = url.lastIndexOf(SLASH);
		if (pos != NOT_EXIST) {
			return url.substring(pos + SLASH_LEN);
		}
		else {
			return url;
		}
	}

	/**
	 * 取得文件的扩展名
	 *
	 * @param url URL地址
	 * @return 文件扩展名
	 */
	public static String getFileExt(String url) {
		int pos = url.lastIndexOf(DOT);
		if (pos != NOT_EXIST) {
			return url.substring(pos).toLowerCase();
		}
		else {
			return getFileName(url);
		}
	}

	/**
	 * 取得文件的Content-Type
	 *
	 * @param filename 文件名
	 * @return
	 */
	public static String getContentType(String filename) {
		FileNameMap map = URLConnection.getFileNameMap();
		return map.getContentTypeFor(filename);
	}

	/**
	 * 根据类路径获取文件绝对路径, classpath => path
	 *
	 * @param classpath
	 * @return
	 */
	public static String getPath(Class<?> clazz, String classpath) {
		AssertUtil.notNull(clazz, "Class");
		AssertUtil.notEmpty(classpath, "ClassPath");
		if (clazz == null) {
			clazz = PathUtil.class;
		}
		var url = clazz.getResource(classpath);
		if (url == null) {
			ClassLoader loader = Thread.currentThread().getContextClassLoader();
			String path = classpath;
			if (classpath.startsWith("/")) {
				path = classpath.substring(1);
			}
			url = loader.getResource(path);
		}
		var path = url.getPath();
		if (path.contains(":")) {
			path = path.substring(1);
		}
		return path;
	}

}
